import { jieba } from '@/lib/jieba';
import { cachedBlocks, tokenize } from '@/server/controllers/jiebaController';
import { getAllBlocks } from '@/server/controllers/secuController';
import { Hono } from 'hono';

export const jiebaRoutes = new Hono()
    .get('/dict', async (c) => {
        const tokens = await getAllBlocks();
        const dictText = tokens.join('\n');
        return c.text(dictText, 200, {
            'Content-Type': 'text/plain; charset=UTF-8'
        });
    })
    .get('/refresh', async (c) => {
        const tokens = await getAllBlocks();
        tokens.forEach((element) => {
            if (!cachedBlocks.includes(element)) cachedBlocks.push(element);
        });
        // console.log('===>', cachedBlocks.length);
        const dict = tokens.map((t) => `${t} 100 nz`);
        const dictBuffer = Buffer.from(dict.join('\n'), 'utf-8');
        jieba.loadDict(dictBuffer);
        return c.text(`${tokens.length} loaded.`, 200, {
            'Content-Type': 'text/plain; charset=UTF-8'
        });
    })
    .post('/dict', async (c) => {
        const { tokens } = await c.req.json();

        if (tokens instanceof Array) {
            const dict = tokens.map((t) => `${t} 100 nz`);
            const dictBuffer = Buffer.from(dict.join('\n'), 'utf-8');
            jieba.loadDict(dictBuffer);
            return c.text(`${tokens.length} loaded.`, 200, {
                'Content-Type': 'text/plain; charset=UTF-8'
            });
        }
        // console.log(body);
        return c.text(`0 loaded.`, 200, {
            'Content-Type': 'text/plain; charset=UTF-8'
        });
    })
    .get('/analyze', async (c) => {
        const { sentence } = c.req.query();
        if (!sentence?.trim()) {
            return c.text('', 200);
        }
        const words = tokenize(sentence, 2);
        // console.log(words);
        return c.text(`${words.join('\n')}`, 200, {
            'Content-Type': 'text/plain; charset=UTF-8'
        });
    });
